package model

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"modbus-go-demo/global"
	"time"
)

// MyWriter 定义自己的Writer
type MyWriter struct {
	logger *logrus.Logger
}

var DB *gorm.DB

func init() {
	dbHost := global.AppConfig.Section("mysql").Key("host").String()
	dbPort := global.AppConfig.Section("mysql").Key("port").String()
	dbUser := global.AppConfig.Section("mysql").Key("user").String()
	dbPwd := global.AppConfig.Section("mysql").Key("passwd").String()
	dbName := global.AppConfig.Section("mysql").Key("database").String()
	charset := global.AppConfig.Section("mysql").Key("charset").String()
	logMode, _ := global.AppConfig.Section("mysql").Key("logMode").Int()
	// &parseTime=true
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&loc=Local", dbUser, dbPwd, dbHost, dbPort, dbName, charset)

	var newLogger logger.Interface
	if logMode == 1 {
		// sql日志写入文件, logrus 实现
		newLogger = logger.New(
			NewMyWriter(),
			logger.Config{
				SlowThreshold: 1 * time.Second,
				LogLevel:      logger.Info,
				Colorful:      false,
			},
		)
	} else {
		// 控制台打印sql日志
		newLogger = logger.Default.LogMode(logger.Info)
	}

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		QueryFields:            true,
		Logger:                 newLogger, // 日志处理
		SkipDefaultTransaction: true,      // 禁用事务, 默认开启
	})

	if err != nil {
		fmt.Println("gorm.Open error: ", err)
		return
	}

	sqlDB, err := db.DB()
	if err != nil {
		fmt.Println("DB.DB() error: ", err)
		return
	}
	//  设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(5)
	//  设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(20)
	//  设置了连接可复用的最大时间。10分钟不用的连接将放入连接池, 连接池满则关闭连接
	sqlDB.SetConnMaxLifetime(time.Minute * 10)
	DB = db
	fmt.Printf("%-32s%-32s\n", "mysql connected", "OK")

}

//实现gorm/logger.Writer接口

func (mw *MyWriter) Printf(format string, v ...interface{}) {
	logStr := fmt.Sprintf(format, v...)
	//利用loggus记录日志
	mw.logger.Info(logStr)
}

func NewMyWriter() *MyWriter {
	return &MyWriter{logger: global.MyLogger}
}
